/*
 * @Date         : 2024-03-11 10:51:32
 * @Description  : web平台相关
 */

import { env } from "@/config/env"
import Track from "@/utils/track"
import { isEmpty } from "@/utils/check"
// #ifdef WEB
import Auth from "@/utils/auth"
import { getWebEnv, getWebEvn } from "@/utils/utils"
// #endif

// 需要缓存的key
const localCacheNames = []
const sessionCacheNames = ["webEvn", "disableWebAuth", "disableWebAuthLogin"]

export default {
  state: {
    // #ifdef WEB
    webEnv: "", // 容器环境
    webEvn: "", // 业务环境
    // #endif
    disableWebAuth: false, // 禁用授权
    disableWebAuthLogin: false // 禁用授权登录
  },
  getters: {
    webEnv: (state) => state.webEnv,
    webEvn: (state) => state.webEvn,
    disableWebAuth: (state) => state.disableWebAuth,
    disableWebAuthLogin: (state) => state.disableWebAuthLogin
  },
  mutations: {
    INIT(state) {
      // 初始化本地缓存
      localCacheNames.forEach((name) => {
        let data = uni.getStorageSync(name)
        if (data) state[name] = data
      })
      // #ifdef WEB
      sessionCacheNames.forEach((name) => {
        let data = window.sessionStorage.getItem(name)
        if (data) {
          try {
            state[name] = JSON.parse(data)
          } catch (error) {
            state[name] = data
          }
        }
      })
      // #endif
    },
    INIT_WEB(state, data) {
      // #ifdef WEB
      state.webEnv = getWebEnv()
      state.webEvn = window.sessionStorage.getItem("webEvn") || getWebEvn()
      if (data.query?.disableWebAuth) {
        state.disableWebAuth = data.query.disableWebAuth
        window.sessionStorage.setItem("disableWebAuth", state.disableWebAuth)
      }
      if (data.query?.disableWebAuthLogin) {
        state.disableWebAuthLogin = data.query.disableWebAuthLogin
        window.sessionStorage.setItem("disableWebAuthLogin", state.disableWebAuthLogin)
      }
      if (data.query?.evn) {
        state.webEvn = getWebEvn()
        window.sessionStorage.setItem("webEvn", state.webEvn)
      }
      // #endif
    },
    // 设置web环境
    SET_WEB_ENV(state, data) {
      state.webEnv = data
      // #ifdef WEB
      window.sessionStorage.setItem("webEnv", state.webEnv)
      // #endif
    },

    // 设置web业务环境
    SET_WEB_EVN(state, data) {
      state.webEvn = data
      // #ifdef WEB
      window.sessionStorage.setItem("webEvn", state.webEvn)
      // #endif
    }
  },
  actions: {
    // 初始化分享信息
    initShare(_, options) {
      // #ifdef WEB
      if (uni.$auth?.sdk) {
        if (uni.$auth.sdk.checkApi("updateAppMessageShareData")) {
          uni.$auth.sdk.core.updateAppMessageShareData({ title: options.title, desc: options.desc, link: options.link, imgUrl: options.imgUrl })
        }
        if (uni.$auth.sdk.checkApi("updateTimelineShareData")) {
          uni.$auth.sdk.core.updateTimelineShareData({ title: options.title, link: options.link, imgUrl: options.imgUrl })
        }
      }

      // #endif
    },
    initWebSdk({ dispatch, commit, rootState }, options) {
      // #ifdef WEB
      return new Promise((resolve, reject) => {
        commit("INIT_WEB", options)
        dispatch("handleNavigationBar")
        const { disableWebAuth, disableWebAuthLogin } = uni.$getUrlParams()
        if (disableWebAuth != 1) {
          uni.$auth = new Auth({ env: uni.getStorageSync("env") || env, debug: rootState.config.debug })
          // 开始初始化
          uni.$auth.ready({
            success: () => {
              const title = rootState.baseInfo?.pageTitle

              if (uni.$auth.sdk.checkApi("setNavigationBarTitle") && title) uni.$auth.sdk.setNavigationBarTitle(title)

              if (isEmpty(disableWebAuthLogin)) {
                // 开始登录
                uni.$auth.login({
                  fail: (err) => {
                    const errStr = uni.$check.isError(err) ? err.toString() : JSON.stringify(err)
                    dispatch("errorLog", { device: JSON.stringify(uni.$systemInfo), content: `[WEB端SDK授权登录失败] ${errStr}`, route: uni.$currentRoute })
                  }
                })
              }
              if (rootState.deco.indexDeco?.config) {
                dispatch("initShare", {
                  title: rootState.deco.indexDeco.config.shareTitle,
                  desc: rootState.deco.indexDeco.config.shareContent,
                  link: window.location.href,
                  imgUrl: rootState.deco.indexDeco.config.shareImage
                })
              }

              resolve()
            },
            fail: (err) => {
              reject(err)
              const errStr = uni.$check.isError(err) ? err.toString() : JSON.stringify(err)
              dispatch("errorLog", { device: JSON.stringify(uni.$systemInfo), content: `[WEB端SDK初始化失败] ${errStr}`, route: uni.$currentRoute })
            }
          })
        }
      })
      // #endif
    },
    initWebTrack({ dispatch, rootState }) {
      return new Promise(async (resolve, reject) => {
        let baseInfo = {}
        try {
          if (rootState.baseInfoReady) {
            baseInfo = rootState.baseInfo
          } else {
            baseInfo = await dispatch("getBaseInfo")
          }
          // eslint-disable-next-line no-empty
        } catch (error) {}
        const mdInfo = baseInfo.mdInfo || {}
        const _env = uni.getStorageSync("env") || env
        uni.$track = new Track({ ...mdInfo, env: _env })
        uni.$track
          .init()
          .then(() => {
            resolve()
          })
          .catch((err) => {
            reject(err)
            const errStr = uni.$check.isError(err) ? err.toString() : JSON.stringify(err)
            dispatch("errorLog", { device: JSON.stringify(uni.$systemInfo), content: `[WEB端埋点初始化失败] ${errStr}`, route: uni.$currentRoute })
          })
      })
    },
    // 处理默认导航栏
    handleNavigationBar({ state }) {
      const evns = ["cib"]
      if (evns.includes(state.webEvn)) {
        document.documentElement.classList.add("show-uni-page-head")
      }
    }
  }
}
